import { defineStore } from 'pinia'
import { getUserMenu } from '@api/user'
import { useUserStore } from '@store/useUserStore'
import { Parent } from '@interface/user'
export const useMenuStore = defineStore('menuId', {
  state: () => {
    return {
      authSlideMenuMap: '',
      authSlideMenuList: [],
    }
  },
  getters: {},
  actions: {
    async getMenu() {
      let res = await getUserMenu(useUserStore().rolePerm);
      let rowMenu = res.data;
      const { authSlideMenuMap, authSlideMenuList } = normalizqSlideMenu(rowMenu)
      console.log(authSlideMenuMap, "authSlideMenuMap");
      console.log(authSlideMenuList, "authSlideMenuList");

      this.authSlideMenuMap = authSlideMenuMap
      this.authSlideMenuList = authSlideMenuList
    }
  },
  persist: {
    enabled: true, //开启数据缓存
    strategies: [
      {
        storage: localStorage,//默认走session
        paths: ['authSlideMenuList','authSlideMenuMap']
      }
    ]
  }
})


function normalizqSlideMenu(routers: any) {
  const authSlideMenuMap = new Map()
  const authSlideMenuList = routers.
    map((route: any) => normalizqSlideMenuItem(route, authSlideMenuMap))
    .filter(Boolean)
  console.log(authSlideMenuList, authSlideMenuList);
  const _authSlideMenuList = [
    createMenRoute({
      path: "/",
      meta: {
        title: "首页"
      }
    }),
    ...authSlideMenuList
  ]
  return {
    authSlideMenuMap,
    authSlideMenuList: _authSlideMenuList
  }
}

function normalizqSlideMenuItem(route, authSlideMenuMap) {
  const _route = createMenRoute(route)
  console.log(route, "route");
  console.log(_route, "_route");
  if (route.type === 0 && route.children) {
    _route.children = route.children
      .map(item => normalizqSlideMenuItem(item, authSlideMenuMap))
      .filter(Boolean)
  }
  authSlideMenuMap.set(_route.path, _route)
  return _route
}

function createMenRoute(route: any) {
  return {
    path: route.path,
    meta: {
      ...route.meta,
      alwaysShow: route.alwaysShow,
      hidden: route.hidden,
      query: route.query,
      redirect: route.redirect,
      type: route.alwaysshow,
    }
  }
}

function createMenRouter(roters: any) {
  return [
    {
      path: "/",
      meta: {
        title: "首页"
      }
    },
    ...roters
  ]
}